package com.yunianvh.mobilecashierweb

import android.Manifest
import android.content.*
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.webkit.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    private lateinit var webView: WebView
    private val CAMERA_PERMISSION_REQUEST_CODE = 1001
    private val NOTIFICATION_LISTENER_REQUEST_CODE = 1002

    // 添加广播接收器用于接收支付通知
    private val paymentReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == "com.yunianvh.mobilecashierweb.PAYMENT_RECEIVED") {
                val amount = intent.getStringExtra("payment_amount") ?: ""
                val platform = intent.getStringExtra("payment_platform") ?: ""

                // 调用WebView中的JavaScript函数处理支付结果
                val jsCode = "javascript:handlePaymentReceived('$amount', '$platform')"
                webView.post {
                    webView.evaluateJavascript(jsCode) { result ->
                        if (result == null || result.contains("error")) {
                            Log.e("WebView", "JavaScript调用失败: $result")
                        } else {
                            Log.d("WebView", "JavaScript调用成功，金额：$amount，平台：$platform")
                        }
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 设置全屏但保留状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)

        setContentView(R.layout.activity_main)

        webView = findViewById(R.id.webview)
        setupWebView()

        // 注册广播接收器
        val intentFilter = IntentFilter("com.yunianvh.mobilecashierweb.PAYMENT_RECEIVED")
        intentFilter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY
        registerReceiver(paymentReceiver, intentFilter)

        // 先直接加载H5页面，不要等待权限获取
        loadCashierPage()

        // 检查并请求摄像头和存储权限
        requestCameraAndStoragePermissions()
    }

    private fun requestCameraAndStoragePermissions() {
        val neededPermissions = mutableListOf<String>()
        
        // 检查摄像头权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED
        ) {
            neededPermissions.add(Manifest.permission.CAMERA)
        }
        
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.S_V2) {
            // 检查存储权限（Android 12及以下）
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
            ) {
                neededPermissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
            ) {
                neededPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
        } else {
            // 检查媒体权限（Android 13及以上）
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
                != PackageManager.PERMISSION_GRANTED
            ) {
                neededPermissions.add(Manifest.permission.READ_MEDIA_IMAGES)
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO)
                != PackageManager.PERMISSION_GRANTED
            ) {
                neededPermissions.add(Manifest.permission.READ_MEDIA_VIDEO)
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO)
                != PackageManager.PERMISSION_GRANTED
            ) {
                neededPermissions.add(Manifest.permission.READ_MEDIA_AUDIO)
            }
        }
        
        if (neededPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                neededPermissions.toTypedArray(),
                CAMERA_PERMISSION_REQUEST_CODE
            )
        } else {
            // 如果不需要请求权限，则直接检查通知权限
            checkNotificationListenerPermission()
        }
    }

    private fun setupWebView() {
        webView.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            databaseEnabled = true
            allowFileAccess = true
            allowContentAccess = true
            builtInZoomControls = false
            displayZoomControls = false
            useWideViewPort = true
            loadWithOverviewMode = true

            // 启用摄像头权限
            mediaPlaybackRequiresUserGesture = false

            // 优化渲染性能
            setRenderPriority(WebSettings.RenderPriority.HIGH)
            
            // 为localStorage设置较大的存储空间（5MB）
            domStorageEnabled = true

            // 设置WebView允许访问文件系统
            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }

        // 优化WebView性能
        webView.isDrawingCacheEnabled = true
        webView.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH
        
        webView.webViewClient = object : WebViewClient() {
            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                Log.e(TAG, "WebView加载失败: $error")
                Toast.makeText(this@MainActivity, "页面加载失败，请检查网络或文件路径", Toast.LENGTH_SHORT).show()
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.d(TAG, "WebView加载完成: $url")
            }
        }

        // 添加JavaScript接口，允许JavaScript调用原生方法
        webView.addJavascriptInterface(object : Any() {
            // 打开微信扫码
            @JavascriptInterface
            fun openWechatScan(amount: String) {
                try {
                    Log.e(TAG, "打开微信扫码: $amount")
                    // 尝试直接打开微信扫码界面
                    val intent = Intent()
                    intent.action = "android.intent.action.VIEW"
                    // 微信扫码界面的Uri
                    val uri = Uri.parse("weixin://scanqrcode")
                    intent.data = uri
                    startActivity(intent)
                } catch (e: Exception) {
                    // 如果无法直接打开，提示用户手动打开微信
                    runOnUiThread {
                        Toast.makeText(this@MainActivity, "请手动打开微信扫码收款", Toast.LENGTH_SHORT).show()
                    }
                }
            }

            // 打开支付宝扫码
            @JavascriptInterface
            fun openAlipayScan(amount: String) {
                try {
                    Log.e(TAG, "打开支付宝扫码: $amount")
                    // 尝试直接打开支付宝扫码界面
                    val intent = Intent()
                    intent.action = "android.intent.action.VIEW"
                    // 支付宝扫码界面的Uri
                    val uri = if (amount.isNotEmpty()) {
                        // 如果有指定金额，带上金额参数
                        Uri.parse("alipayqr://platformapi/startapp?saId=10000007&amount=$amount")
                    } else {
                        // 没有指定金额，打开普通扫码
                        Uri.parse("alipayqr://platformapi/startapp?saId=10000007")
                    }
                    intent.data = uri
                    startActivity(intent)
                } catch (e: Exception) {
                    // 如果无法直接打开，提示用户手动打开支付宝
                    runOnUiThread {
                        Toast.makeText(this@MainActivity, "请手动打开支付宝扫码收款", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }, "NativeInterface")

        webView.webChromeClient = object : WebChromeClient() {
            override fun onPermissionRequest(request: PermissionRequest?) {
                if (request != null) {
                    // 自动授予所有需要的权限
                    val requestedResources = request.resources
                    val grantedResources = mutableListOf<String>()
                    
                    for (resource in requestedResources) {
                        when (resource) {
                            PermissionRequest.RESOURCE_VIDEO_CAPTURE -> {
                                grantedResources.add(resource)
                            }
                            PermissionRequest.RESOURCE_AUDIO_CAPTURE -> {
                                grantedResources.add(resource)
                            }
                            // 可以根据需要添加其他资源类型
                        }
                    }
                    
                    if (grantedResources.isNotEmpty()) {
                        request.grant(grantedResources.toTypedArray())
                    }
                }
            }

            // 优化摄像头切换页面时的响应速度
            override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
                super.onShowCustomView(view, callback)
            }

            override fun onHideCustomView() {
                super.onHideCustomView()
            }
        }
    }

    // 检查通知监听权限
    private fun checkNotificationListenerPermission() {
        val isEnabled = try {
            val enabledListeners = Settings.Secure.getString(
                contentResolver,
                "enabled_notification_listeners"
            ) ?: ""
            val packageName = packageName
            val className = NeNotificationService::class.java.name
            enabledListeners.contains("$packageName/$className")
        } catch (e: Exception) {
            false
        }

        if (!isEnabled) {
            try {
                // 尝试跳转到通知监听设置页面
                val intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivityForResult(intent, NOTIFICATION_LISTENER_REQUEST_CODE)
            } catch (e: ActivityNotFoundException) {
                // 如果标准方式失败，尝试备用方案
                try {
                    val intent = Intent()
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    val componentName = ComponentName(
                        "com.android.settings",
                        "com.android.settings.Settings\$NotificationAccessSettingsActivity"
                    )
                    intent.component = componentName
                    intent.putExtra(":settings:show_fragment", "NotificationAccessSettings")
                    startActivity(intent)
                } catch (e1: Exception) {
                    Toast.makeText(this, "对不起，您的设备暂不支持此功能", Toast.LENGTH_SHORT).show()
                }
            }
            Toast.makeText(this, "请开启通知监听权限以启用自动收款功能", Toast.LENGTH_LONG).show()
        }
    }


    private fun loadCashierPage() {
        webView.loadUrl("file:///android_asset/cashier.html")
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        when (requestCode) {
            CAMERA_PERMISSION_REQUEST_CODE -> {
                // 检查是否所有请求的权限都被授予
                val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
                
                if (allGranted) {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "某些权限未授予，可能会影响部分功能", Toast.LENGTH_SHORT).show()
                }
                
                // 检查通知监听权限
                checkNotificationListenerPermission()
                return
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            NOTIFICATION_LISTENER_REQUEST_CODE -> {
                // 用户从通知监听设置返回，检查权限是否已授予
                checkNotificationListenerPermission()
            }
        }
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onPause() {
        super.onPause()
        // 暂停WebView以释放资源
        webView.onPause()
    }

    override fun onResume() {
        super.onResume()
        // 恢复WebView
        webView.onResume()
    }

    override fun onDestroy() {
        // 注销广播接收器
        unregisterReceiver(paymentReceiver)
        webView.destroy()
        super.onDestroy()
    }
}